<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>设备管理</title>
    <jsp:include page="../inc/css.jsp"/>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <!-- /.card-header -->
                        <div class="card-header">
                            <button type="button" title="新增设备" class="btn btn-success" onclick="_deviceList.fn.addInfo()">新增设备</button>

                            <c:if test="${sessionScope.session_master_id == 1}">
                                <button type="button" title="同步原始数据" class="btn btn-info" onclick="_deviceList.fn.syncData()">同步原始数据</button>
                                <button type="button" title="同步转发数据" class="btn btn-primary" onclick="_deviceList.fn.syncDeviceShareData()">同步转发数据</button>
                                <button type="button" title="同步告警规则数据" class="btn btn-warning" onclick="_deviceList.fn.syncAlarmRuleData()">同步告警规则数据</button>
                                <button type="button" title="同步预警消息数据" class="btn btn-success" onclick="_deviceList.fn.syncAlarmMessageData()">同步预警消息数据</button>
                                <button type="button" title="清理重复预警消息" class="btn btn-danger" onclick="_deviceList.fn.cleanRepeatData()">清理重复告警规则</button>
                                <button type="button" title="刷新设备汇总数据" class="btn btn-primary" onclick="_deviceList.fn.refreshDeviceStaticData()">刷新设备汇总数据</button>
                            </c:if>

                            <div class="form-inline" style="margin-top: 10px;">
                                <div class="form-group">
                                    <select id="searchCompanyList" class="form-control" style="margin-right: 10px;">
                                        <option value="">全部公司</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <input id="searchKeyWord" placeholder="设备名称或编号" class="form-control" style="margin-right: 10px;">
                                </div>
                                <div class="form-group">
                                    <select id="searchDeviceTypeList" class="form-control" style="margin-right: 10px;">
                                        <option value="">全部类型</option>
                                        <option value="1">废气排口</option>
                                        <option value="2">废水排口</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <select id="searchStateTypeList" class="form-control" style="margin-right: 10px;">
                                        <option value="">全部类别</option>
                                        <option value="1">国控排口</option>
                                        <option value="2">内控排口</option>
                                    </select>
                                </div>
                                <button type="button" title="查询" class="btn btn-info" style="margin-left: 10px;" onclick="_deviceList.fn.reloadData()">查询</button>
                                <button type="button" title="重置搜索条件并查询" class="btn btn-success" style="margin-left: 10px;" onclick="_deviceList.fn.resetAndReloadData()">重置</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover" id="dataTables" style="width: 99%">
                                    <colgroup>
                                        <c:if test="${sessionScope.session_master_id == 1}">
                                            <col class="gradeA even"/>
                                        </c:if>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                        <col class="gradeA odd"/>
                                        <col class="gradeA even"/>
                                    </colgroup>
                                    <thead>
                                    <tr>
                                        <c:if test="${sessionScope.session_master_id == 1}">
                                            <th>所属公司</th>
                                        </c:if>
                                        <th>设备名称</th>
                                        <th>设备编号</th>
                                        <th style="width: 80px;">设备类型</th>
                                        <th style="width: 80px;">设备类别</th>
                                        <th style="max-width: 150px;">录入时间</th>
                                        <th style="max-width: 50px">顺序</th>
                                        <th style="max-width: 50px">状态</th>
                                        <th style="max-width: 150px">最近时间</th>
                                        <th style="min-width: 160px">操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <!-- /.card-body -->
                    </div>
                    <!-- /.card -->
                </div>
                <!-- /.col -->
            </div>
            <!-- /.row -->
        </section>
        <!-- /.content -->
    </div>
</div>
<!-- ./wrapper -->

<div class="modal inModal fade" id="deviceShareModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">数据转发详情</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">转发地址：</label>

                        <div class="col-8">
                            <input type="text" id="deviceShareIp" maxlength="30" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">转发端口：</label>

                        <div class="col-8">
                            <input type="text" id="deviceSharePort" maxlength="10" class="form-control" style="width: 95%"/>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_deviceList.fn.saveShareInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal inModal fade" id="deviceModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">设备详情</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <input type="hidden" id="deviceId"/>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">设备类型：</label>

                        <div class="col-8">
                            <select id="deviceTypeList" class="form-control" style="width: 95%">
                                <option value="1">废气排口</option>
                                <option value="2">废水排口</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">设备类别：</label>

                        <div class="col-8">
                            <select id="stateTypeList" class="form-control" style="width: 95%">
                                <option value="2">内控</option>
                                <option value="1">国控</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">公司：</label>

                        <div class="col-8">
                            <select id="companyList" class="form-control" style="width: 95%">
                                <option value="">请选择公司</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">设备名称：</label>

                        <div class="col-8">
                            <input type="text" id="deviceName" maxlength="30" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">设备编号：</label>

                        <div class="col-8">
                            <input type="text" id="deviceCode" maxlength="40" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">显示顺序：</label>

                        <div class="col-8">
                            <input type="number" id="deviceShowIndex" step="1" min="1" max="99" maxlength="2" oninput="_deviceList.fn.filterPositiveInteger(this)" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">转发IP：</label>

                        <div class="col-8">
                            <input type="text" id="forwardAddress" maxlength="30" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">转发端口：</label>

                        <div class="col-8">
                            <input type="number" id="forwardPort" maxlength="10" class="form-control" style="width: 95%"/>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">显示状态：</label>

                        <div class="col-8">
                            <select id="showStatusList" class="form-control" style="width: 50%" onchange="_deviceList.fn.updateDeviceShowStatus(this)">
                                <option value="1">显示</option>
                                <option value="0">隐藏</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">零值预警：</label>

                        <div class="col-8">
                            <select id="zeroAlarmStatusList" class="form-control" style="width: 50%" onchange="_deviceList.fn.updateZeroAlarmStatus()">
                                <option value="0">关闭</option>
                                <option value="1">开启</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">预警开关：</label>

                        <div class="col-8">
                            <select id="alarmStatus" class="form-control" style="width: 50%" onchange="_deviceList.fn.updateAlarmStatus()">
                                <option value="1">开启</option>
                                <option value="0">关闭</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" onclick="_deviceList.fn.saveForwardInfo()">保存转发</button>
                <button type="button" class="btn btn-primary" onclick="_deviceList.fn.saveInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- page script -->
<script type="text/javascript">
    let _deviceList = {
        v: {
            list: [],
            dTable: null,
            companyId: 0
        },
        fn: {
            init: function () {
                let masterCompanyId = $('#masterCompanyId').val();

                if (Number(masterCompanyId) > 0) {
                    _deviceList.v.companyId = Number(masterCompanyId);

                    $('#companyList').css('display', 'none');
                    $('#companyList').parent().parent().css('display', 'none');
                    $('#searchCompanyList').css('display', 'none');
                } else {
                    _deviceList.fn.getCompanyList();
                }

                _deviceList.fn.dataTableInit();
            },
            getCompanyList: function () {
                $.post('common/companyList', {
                    id: 1
                }, function (result) {
                    if (result.length > 0) {
                        let content = '';
                        $.each(result, function (i, item) {
                            content += '<option value="' + item.id + '">' + item.name + '</option>';
                        });

                        $('#companyList').append(content);
                        $('#searchCompanyList').append(content);
                    } else {
                        info("暂无公司数据", "error");
                    }
                });
            },
            reloadData: function () {
                _deviceList.v.list = [];
                _deviceList.v.dTable.DataTable().ajax.reload(null, false);
            },
            resetAndReloadData: function () {
                $('#searchCompanyList').val('');
                $('#searchKeyWord').val('');
                $('#searchDeviceTypeList').val('');
                $('#searchStateTypeList').val('');

                _deviceList.fn.reloadData();
            },
            dataTableInit: function () {
                _deviceList.v.dTable = $tutu.dataTable($('#dataTables'), {
                    "processing": true,
                    "serverSide": true,
                    "autoWidth": true,//自动计算宽度
                    "lengthChange": false,//是否允许用户改变表格每页显示的记录数
                    "searching": false,
                    "ordering": false,
                    "ajax": {
                        "url": "backend/device/list",
                        "type": "POST"
                    },
                    "language": $tutu.v.dataTableL,
                    "columns": [
                        <c:if test="${sessionScope.session_master_id == 1}">
                        {
                            "data": "company",
                            render: function (data) {
                                if (null !== data && data !== "") {
                                    return formatStr(data.name, 10);
                                } else {
                                    return "";
                                }
                            }
                        },
                        </c:if>
                        {
                            "data": "name",
                            render: function (data) {
                                if (null !== data && data !== "") {
                                    return formatStr(data, 10);
                                } else {
                                    return "";
                                }
                            }
                        },
                        {"data": "code"},
                        {
                            "data": "deviceType",
                            render: function (data) {
                                if (data === 1) {
                                    return '废气';
                                } else {
                                    return '废水';
                                }
                            }
                        },
                        {
                            "data": "stateType",
                            render: function (data) {
                                if (data === 1) {
                                    return '国控';
                                } else {
                                    return '内控';
                                }
                            }
                        },
                        {
                            "data": "createTime",
                            render: function (data) {
                                return crtTimeFtt(data);
                            }
                        },
                        {"data": "showIndex"},
                        {
                            "data": "onlineStatus",
                            render: function (data) {
                                if (null === data || '' === data || typeof data === "undefined" || data === 0) {
                                    return '<span style="color: red;">离线</span>';
                                } else {
                                    return '<span style="color: green;">在线</span>';
                                }
                            }
                        },
                        {
                            "data": "lastOnlineTime",
                            render: function (data) {
                                return crtTimeFtt(data);
                            }
                        },
                        {"data": null}
                    ],
                    /*添加小插件*/
                    "columnDefs": [
                        {
                            "data": null,
                            "defaultContent": "<button type='button' title='查看最新数据' class='btn btn-primary btn-sm showData'><i class='fa fa-eye'></i></button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' title='告警规则列表' class='btn btn-info btn-sm childList'><i class='fa fa-list'></i></button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' style='display: none;' title='编辑' class='btn btn-primary btn-sm edit'><i class='fa fa-edit'></i></button>" +
                                "&nbsp;&nbsp;" +
                                "<button type='button' style='display: none;' title='删除' class='btn btn-danger btn-sm delete'><i class='fa fa-remove'></i></button>",
                            "targets": -1
                        }
                    ],
                    /*展示数据格式化*/
                    "createdRow": function (row, data, index) {
                        _deviceList.v.list.push(data);
                    },
                    stateSave: true, // 启用状态保存
                    stateSaveCallback: function (settings, data) {
                        localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data));
                    },
                    stateLoadCallback: function (settings) {
                        return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance));
                    },
                    /*回调函数*/
                    rowCallback: function (row, data) {
                        $('td', row).last().find(".showData").click(function () {
                            if (null !== data.company && data.company !== "") {
                                if (data.onlineStatus === 1) {
                                    window.location.href = 'backend/device/dataInfo?id=' + data.id + '&pageNum=' + $tutu.currentPage;
                                } else {
                                    info('设备已离线，暂时无法查看设备数据', "error");
                                }
                            } else {
                                info('请先为该设备分配所属公司', "error");
                            }
                        });

                        $('td', row).last().find(".childList").click(function () {
                            window.location.href = 'backend/device/child/index?deviceCode=' + data.code + '&pageNum=' + $tutu.currentPage;
                        });

                        let loginMasterId = $('#loginMasterId').val();

                        if (loginMasterId === '1') {
                            $('td', row).last().find(".edit").css('display', '');
                            $('td', row).last().find(".delete").css('display', '');

                            $('td', row).last().find(".edit").click(function () {
                                _deviceList.fn.editInfo(data);
                            });

                            $('td', row).last().find(".delete").click(function () {
                                _deviceList.fn.delInfo(data.id);
                            });
                        }
                    },
                    /*带参数*/
                    "fnServerParams": function (aoData) {
                        _deviceList.v.list = [];

                        if (_deviceList.v.masterCompanyId > 0) {
                            aoData.searchCompanyId = _deviceList.v.masterCompanyId;
                        } else {
                            aoData.searchCompanyId = $('#searchCompanyList').val();
                        }

                        aoData.deviceType = $('#searchDeviceTypeList').val();
                        aoData.stateType = $('#searchStateTypeList').val();
                        aoData.keyWord = $('#searchKeyWord').val();
                    },
                    "fnDrawCallback": function (data) {
                        $tutu.uiForm(data);
                    }
                });
            },
            saveForwardInfo: function () {
                let address = $('#forwardAddress').val();
                let port = $('#forwardPort').val();

                if (address === '') {
                    info('请输入转发IP地址', "error");
                    return;
                }

                if (port === '' || Number(port) <= 0) {
                    info('请输入转发端口', "error");
                    return;
                }

                if (Number(port) <= 0) {
                    info('转发端口格式错误', "error");
                    return;
                }

                startLoading();

                $.post('backend/device/saveForward', {
                    id: $('#deviceId').val(),
                    address: address,
                    port: port
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("转发信息已保存", "success");

                        $("#deviceModal").modal("hide");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            saveInfo: function () {
                let companyId = _deviceList.v.companyId;
                if (companyId === 0) companyId = $('#companyList').val();
                let name = $('#deviceName').val();
                let code = $('#deviceCode').val();
                let showIndex = $('#deviceShowIndex').val();

                if (companyId === '') {
                    info('请选择所属公司', "error");
                    return;
                }

                if (name === '') {
                    info('请输入设备名称', "error");
                    return;
                }

                if (code === '') {
                    info('请输入设备编号', "error");
                    return;
                }

                if (!/^[1-9]\d*$/.test(showIndex)) {
                    info('请输入正确的设备显示顺序编号', "error");
                    return;
                }

                startLoading();

                $.post('backend/device/save', {
                    id: $('#deviceId').val(),
                    deviceType: $('#deviceTypeList').val(),
                    stateType: $('#stateTypeList').val(),
                    companyId: companyId,
                    showIndex: showIndex,
                    name: name,
                    code: code
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("信息已保存", "success");

                        $("#deviceModal").modal("hide");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            editInfo: function (data) {
                $('#deviceId').val(data.id);
                $('#deviceTypeList').val(data.deviceType);
                $('#stateTypeList').val(data.stateType);
                $('#deviceName').val(data.name);
                $('#deviceShowIndex').val(data.showIndex);
                $('#deviceCode').val(data.code).prop("disabled", true);
                if (null != data.company) {
                    $('#companyList').val(data.company.id);
                } else {
                    $('#companyList').val('');
                }
                $('#zeroAlarmStatusList').val(data.zeroAlarmStatus);
                $('#showStatusList').parent().parent().css('display', '');
                $('#showStatusList').val(data.showStatus);

                $("#deviceModal").modal("show");
            },
            syncData: function () {
                $.post('backend/device/sync', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("设备基础信息已同步", "success");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            syncDeviceShareData: function () {
                $.post('backend/device/syncDeviceShare', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("设备转发信息已同步", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            syncAlarmRuleData: function () {
                $.post('backend/alarmRule/sync', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("告警规则已同步", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            syncAlarmMessageData: function () {
                $.post('backend/alarmMessage/sync', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("预警消息已同步", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            cleanRepeatData: function () {
                $.post('backend/alarmRule/cleanRepeatData', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("重复告警规则已清理", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            refreshDeviceStaticData: function () {
                $.post('backend/device/refreshDeviceStaticData', {
                    id: 1
                }, function (result) {
                    if (result.code === 0) {
                        info("设备汇总数据已刷新", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            addInfo: function () {
                $('#deviceId').val('');
                $('#deviceName').val('');
                $('#deviceCode').val('').prop("disabled", false);
                $('#companyList').val('');
                $('#deviceShowIndex').val(1);
                $('#zeroAlarmStatusList').val(0);
                $('#showStatusList').parent().parent().css('display', 'none');

                $("#deviceModal").modal("show");
            },
            updateDeviceInfo: function () {
                startLoading();

                $.post('backend/device/updateInfo', {
                    id: 1
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备信息已刷新", "success");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            updateDeviceShowStatus: function (self) {
                startLoading();

                $.post('backend/device/updateShowStatus', {
                    deviceCode: $('#deviceCode').val(),
                    type: $(self).val()
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备显示状态已变更", "success");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            updateZeroAlarmStatus: function () {
                startLoading();

                $.post('backend/device/updateZeroAlarmStatus', {
                    deviceCode: $('#deviceCode').val(),
                    status: $('#zeroAlarmStatusList').val()
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备零值预警状态已变更", "success");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            updateAlarmStatus: function () {
                startLoading();

                $.post('backend/device/updateAlarmStatus', {
                    deviceCode: $('#deviceCode').val(),
                    status: $('#alarmStatus').val()
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备预警状态已变更", "success");

                        _deviceList.fn.reloadData();
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            delInfo: function (id) {
                swal({
                    title: "您确定要删除这个设备吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "是的，删除！",
                    cancelButtonText: "不，取消",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        startLoading();

                        $.post('backend/device/del', {
                            id: id
                        }, function (result) {
                            endLoading();

                            if (result.code === 0) {
                                swal("删除成功！", "您已经删除了这个设备。", "success");

                                _deviceList.fn.reloadData();
                            } else {
                                info(result.msg, "error");
                            }
                        });
                    } else {
                        swal("已取消", "您取消了删除操作！", "error");
                    }
                })
            },
            filterPositiveInteger: function (self) {
                $(self).val($(self).val()
                    .replace(/[^0-9]/g, '')    // 移除非数字
                    .replace(/^0+/, '')        // 去除前导零
                    .substring(0, 10));         // 限制长度（可选）
            }
        }
    };

    $(document).ready(function () {
        _deviceList.fn.init();

        window.onload = function () {
            checkSelectMenu("deviceLi");

            loadMenuColor('deviceLi');
        }
    });
</script>
</body>
</html>